<template>
  <div class="print">
    <iframe
      id="iframe"
      style="display: none; width: 100%; height: auto"
      frameborder="0"
    ></iframe>
  </div>
</template>
<script>
// import { styleOnload } from '../utils'
export default {
  name: 'PrintView',
  props: {},
  watch: {},
  methods: {
    setBodyHtml(html) {
      const document = window.document
      const iframe = window.frames[0]
      iframe.document.head.innerHTML = document.head.innerHTML // 获取当前文档的头部给iframe
      iframe.document.body.innerHTML = html // 把传过来的html给iframe头部
      // console.log(iframe.document, '---iframe.document')

      let arr = document.getElementsByTagName('tr')
      console.log(arr)
      let heightNum = 0
      let onePage = 800 //第一页的高度
      for (let i in arr) {
        heightNum += arr[i].offsetHeight
        if (heightNum > onePage) {
          // this.thead[i] = true
          heightNum = arr[i].offsetHeight
          onePage = 1500 //第二页高度
        }
      }
      // 图片和样式加载完成
      Promise.all([this.loadStyle(), this.loadImage()]).then(() => {
        // console.log(res)
        //   打印
        iframe.window.print()
      })
    },
    loadStyle() {
      const iframe = window.frames[0]
      const styles = iframe.document.head.getElementsByTagName('style') // <style>
      const links = iframe.document.head.querySelectorAll(
        'link[type="text/css"]'
      ) // <link>
      let str = ''
      str += '<style>html,body,div{height: auto!important;}</style>'
      let arrs = []
      arrs = arrs.concat(...styles, ...links)
      for (let i = 0; i < arrs.length; i++) {
        str += arrs[i].outerHTML
      }
      // eslint-disable-next-line no-unused-vars
      str += '<style>html,body,div{height: auto!important;}</style>'
      // return new Promise((resolve) => {
      //   for (let i = 0; i < arrs.length; i++) {
      //     styleOnload(arrs[i], () => {
      //       if (i === arrs.length - 1) {
      //         console.log('style 样式加载完成')
      //         resolve('style 样式加载完成')
      //       }
      //     })
      //   }
      // })
    },
    loadImage() {
      const iframe = window.frames[0]
      const imgs = iframe.document.body.getElementsByTagName('img') // <img>
      console.log(imgs)
      return new Promise((resolve) => {
        for (let i = 0; i < imgs.length; i++) {
          imgs[i].onload = function () {
            if (i === imgs.length - 1) {
              console.log('img 加载完成')
              resolve('img 加载完成')
            }
          }
        }
      })
    },
  },
}
</script>
